package com.mobialia.socialmediademo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.Html;
import android.util.Log;

import com.facebook.android.Facebook;

public class FacebookProvider {
	public final static String TAG = "FacebookProvider";

	final String appId = "219172308103195";

    Facebook fb = new Facebook(appId);
    
    HttpClient client = new DefaultHttpClient();
    
	SimpleDateFormat dateFormat;
    
	String accessToken;
	
	public FacebookProvider() {
		dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz", Locale.ENGLISH);
		dateFormat.setLenient(true);
	}

    private Update json2Update(JSONObject object) throws Exception {    	
    	JSONObject user = object.getJSONObject("from");
		Update update = new Update();
		update.setMessage((object.has("to") ? "(" + object.getJSONObject("to").getJSONArray("data").getJSONObject(0).getString("name") + ") " : "") +
				(object.has("message") ? Html.fromHtml(object.getString("message")).toString() : ""));
		update.setUserId(user.getString("name"));
		update.setUserName(user.getString("name"));
		update.setTimeStamp(dateFormat.parse(object.getString("created_time")).getTime());
		update.setImageUrl("http://graph.facebook.com/"+user.getString("id")+"/picture");
		return update;
    }
    
    public ArrayList<Update> getUpdates() {
    	Log.d(TAG, "getUpdates()");
    	
    	ArrayList<Update> updates = new ArrayList<Update>();
    	
    	fb.setAccessToken(accessToken);
    	
    	try {
    		Bundle parameters = new Bundle();
    		String res = fb.request("/me/home", parameters);
    		JSONObject object = new JSONObject(res);
    		JSONArray data = object.getJSONArray("data");
    		
    		for (int i = 0; i < data.length(); i++) {
    			JSONObject messageObject = data.getJSONObject(i);
    			if (messageObject.has("message")) {
    				updates.add(json2Update(messageObject));
    			}
    		}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return updates;
    }
 
}